/**
 * Captain
 * © 2017 Captain copyright，All rights reserved.
 * http://www.sccaptain.com.cn
 *
 * JAVA : 8
 * 文  件  名: FakeUserDetailsService.java
 * 创  建  人: Roc Zheng (roc.djz@gmail.com)
 * 创建时间: 2017年8月2日 下午1:32:47
 * 版         本: 1.0.0
 * 备         注:
 * 修订历史:
 */
package com.material.c2c.web.sys.security;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.cpt.security.identity.account.model.AccountUserDetails;

/**
 *
 *
 * @since 1.0
 * @version 1.0
 * @author Roc Zheng (roc.djz@gmail.com)
 */
public class RegistrationAppUserDetailsService implements UserDetailsService {
  private UserDetailsService userDetailsService;

  /**
   *
   * @param userDetailsService
   *
   * @since 1.0
   * @version 1.0
   * @author Roc Zheng (roc.djz@gmail.com)
   */
  public void setUserDetailsService(UserDetailsService userDetailsService) {
    this.userDetailsService = userDetailsService;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    UserDetails user = userDetailsService.loadUserByUsername(username);

    RegistrationApplicationUser appUser = null;
    if (user instanceof AccountUserDetails) {
      AccountUserDetails userDetails = (AccountUserDetails) user;
      appUser = new RegistrationApplicationUser(userDetails.getUsername(), userDetails.getPassword(), userDetails.getId(),
          userDetails.getEmail(), userDetails.getRealName(), userDetails.getPhoneNumber(), userDetails.isEnabled(),
          userDetails.isAccountNonLocked(), userDetails.getAuthorities(), userDetails.getPermissions());
    } else {
      appUser = new RegistrationApplicationUser(user.getUsername(), user.getPassword(), user.isEnabled(), user.isAccountNonExpired(), user.isCredentialsNonExpired(),
          user.isAccountNonLocked(), user.getAuthorities());
    }
    return appUser;
  }
}
